<?php

class UsersController extends AdminController {


	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'Users'),
		));
	}

	public function actionCreate() {
		$model = new Users;


		if (isset($_POST['Users'])) {
			$model->setAttributes($_POST['Users']);

            if (1 == $model->approved) {
                $model->approved_date = time();
                $model->approved_user = Yii::app()->user->id;
            }
            $model->author_id = Yii::app()->user->id;
            
			if ($model->save()) {
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'Users');


		if (isset($_POST['Users'])) {
            $before_approved = $model->approved;
            $before_password = $model->password;
            
			$model->setAttributes($_POST['Users']);
            
            if ($before_approved != $model->approved) {
                if (1 == $model->approved) {
                    $model->approved_date = time();
                    $model->approved_user = Yii::app()->user->id;
                } else {
                    $model->approved_date = null;
                    $model->approved_user = null;
                }               
            }
            if ($before_password != $model->password) {
				$model->password = crypt($model->password, Controller::blowfishSalt());
            }
            
			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			//$this->loadModel($id, 'Users')->delete();
			$model = $this->loadModel($id, 'Users');
			$model->deleted = 1;
			if ($model->save()) {
				if (!Yii::app()->getRequest()->getIsAjaxRequest()) $this->redirect(array('admin'));
			}				

		} else
			throw new CHttpException(400, AdminModule::t('Некорректный запрос.'));
	}

	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Users');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		$model = new Users('search');
		$model->unsetAttributes();
		$model->deleted = 0;
		if (isset($_GET['Users']))
			$model->setAttributes($_GET['Users']);

		$this->render('admin', array(
			'model' => $model,
		));
	}

}